package models

import (
	"encoding/json"
	"fmt"
	"loveoneanother.at/tiedot/db"
	"os"
	"log"
)

var (
	DbPath string
)

func InitDb(root string) {
	//os.RemoveAll(dir)
	dbroot := root + DB_DIR
	if _,err := os.Stat(dbroot); os.IsNotExist(err) {
		fmt.Println("creating db files...")
		os.MkdirAll(dbroot, 0777)

		myDB, err := db.OpenDB(dbroot)
		if err != nil {
			panic(err)
		}
		// Gracefully close database
		defer myDB.Close()

		// Create collection
		if err := myDB.Create(DB_FOLDERS); err != nil {
			panic(err)
		}
		
	}
	DbPath = dbroot
}

func SyncDb(dirs map[string]*Imgdir) {
	myDB, err := db.OpenDB(DbPath)
	if err != nil {
		panic(err)
	}
	// Gracefully close database
	defer myDB.Close()

	F := myDB.Use(DB_FOLDERS)

	// Execute query
	result := make(map[uint64]struct{})
	var query interface{}
	json.Unmarshal([]byte(`["all"]`), &query)
	if err := db.EvalQueryV2(query, F, &result); err != nil {
		panic(err)
	}

	for id, _ := range result {
		// query results are in map keys
		log.Println("Query returned document ID ", id)

		var dbdir Imgdir
		if err := F.Read(id, &dbdir); err != nil {
			panic(err)
		}
		
		if localdir, ok := dirs[dbdir.Path]; ok {
			// 找到
			if localdir.Hash != dbdir.Hash {
				tmpdir := SyncImgdir(localdir, &dbdir)
				_, err := F.Update(id, tmpdir)
				if err != nil {
					panic(err)
				}
			}
			localdir.Stats = SYNC
		} else {
			//miss
			dbdir.Stats = MISS
			_, err := F.Update(id, dbdir)
			if err != nil {
				panic(err)
			}
		}
	}

	for _, dir := range dirs {
		if dir.Stats == UNKNOWN {
			dir.Stats = SYNC
			_, err := F.Insert(dir)
			if err != nil {
				panic(err)
			}
		}
	}

}

func DbGetAllFolders() (map[uint64]*Imgdir, error) {
	myDB, err := db.OpenDB(DbPath)
	if err != nil {
		panic(err)
	}
	// Gracefully close database
	defer myDB.Close()

	F := myDB.Use(DB_FOLDERS)

	F.Index([]string{"Stats"})
	// Execute query
	result := make(map[uint64]struct{})
	var query interface{}
	json.Unmarshal([]byte(`{"eq":1, "in":["Stats"]}`), &query)
	if err := db.EvalQueryV2(query, F, &result); err != nil {
		panic(err)
	}	
	
	log.Println("--------", len(result))

	imgdirs := make(map[uint64]*Imgdir)
	for id, _ := range result {
		var dbdir Imgdir
		if err := F.Read(id, &dbdir); err != nil {
			panic(err)
		}
		imgdirs[id] = &dbdir
	}
	return imgdirs, nil
}

func DbGetFolder(id uint64) (*Imgdir, error) {
	myDB, err := db.OpenDB(DbPath)
	if err != nil {
		panic(err)
	}
	// Gracefully close database
	defer myDB.Close()

	F := myDB.Use(DB_FOLDERS)

	var dbdir Imgdir
	if err := F.Read(id, &dbdir); err != nil {
		return nil, err
	}

	return &dbdir, nil
}













